<?php
class MainModel extends CActiveRecord {

	public static function model($className=__CLASS__){
		return parent::model($className);
	}
	
	function getModelName(){
		return get_class($this);
	}
	
	//очищаем строки перед выводом
	function clearRender($string='',$limit=''){
		//TODO не работает трим. проверить обработку данных перед выводом мета тегов (дескрипшн в данном случае)
		return $string;
		$string = trim($string);
		$string = htmlspecialchars($string);
		$string = strip_tags($string);
		if(!$limit){
			return $string;
		}else{
			$string = explode(' ', $string);
			if(count($string) > $limit){
				$string = join(' ', array_slice($string, 0, $limit));
				return $string;
			}else{
				return $string;
			}
		}
	}

	function title($id='',$page=1){
        $item = $this->findbypk($id);
		if($item['alt_title']){
			$return = $this->clearRender($item['alt_title']);
		}elseif($item['title']){
			$return = $this->clearRender($item['title']);
		}
		if($page > 1){
			$return .= ' (стр. '.$page.')';
		}
		return $return.' | ';
	}
	
	function keywords(){
		return 'Общая функция кейвордов на уровне системы';
	}
	
	function description($id=''){
		$current = $this->findbypk($id);
		if(isset($current->alt_description) AND $current->alt_description != ''){
			$return = $this->clearRender($current->alt_description,30);
			return $return;
		}elseif(isset($current->description) AND $current->description != ''){
			$return = $this->clearRender($current->description,30);
			return $return;
		}else{
			return 'Общее описание на уровне системы';
		}
	}

	function getGallery($count='',$type='item'){
		$images = Yii::app()->db->createCommand()
			->select('*')
			->from('{{content_file}}')
			->join('{{file}}', '{{file}}.id={{content_file}}.file')
			->where('item=:id AND model=:model', array(':id'=>$this->id,':model'=>$this->getModelName()));
		if($count){
			$images->limit(1);
		}
		$images = $images->queryAll();
		if(count($images) > 0){
			$return = array();
			foreach($images as $image){
				$return[] = $image['name'].'.'.$image['extension'];
			}
			return $return;
		}else{
			return false;
		}
	}
	
	function getCover(){
		$return = $this->getGallery(1);
		return $return['0'];
	}


       /**
    * Поле которое содержит дату создания записи
    * @var string
    */
        protected $_createdField = 'created';

       /**
    * Поле которое содержит дату редактирования записи
    * @var string
    */
        protected $_updatedField = 'updated';

        /**
    * @var string|null последнее собщение об ошибке
    */
        protected $_lastErrorMessage = null;

        /**
    * @var CDbTransaction|null текущая транзакция
    */
        static protected $_transaction;

        /**
    * Проставляет дату создания и модификации записи
    *
    * @return bool
    */
        protected function beforeSave() {
         if (!parent::beforeSave()) {
         return false;
         }

            if (isset($this->metadata->tableSchema->columns[$this->_updatedField])) {
                $this->{$this->_updatedField} = time();
            }
         if ($this->isNewRecord) {
         if (isset($this->metadata->tableSchema->columns[$this->_createdField])) {
                 $this->{$this->_createdField} = time();
         }
            }

            return true;
        }

        /**
    * Генерация slug(alias) для записи при наличии поля slug и title
    *
    * @return bool
    */
        public function beforeValidate() {
            if (!parent::beforeValidate()) {
                return false;
            }
            if (isset($this->metadata->tableSchema->columns['permalink'], $this->metadata->tableSchema->columns['title'])&& empty($this->permalink)) {
                $this->permalink = $this->createUrlName($this->title);
            }
            $this->safePermalink();
            return true;
        }

        /**
    * Устанавливает последнее сообщение об ошибке
    *
    * @param string $message
    * @return bool false
    */
        public function onError($message = null) {
         $this->_lastErrorMessage = $message;
         return false;
        }

        /**
    * Возвращает последнее сообщение об ошибке
    * @return string
    */
        public function getLastErrorMessage() {
         if (empty($this->_lastErrorMessage)) {
         $this->_lastErrorMessage = 'Ошибка в процессе выполнения';
         }
         return $this->_lastErrorMessage;
        }


        /**
    * Начало транзакции
    *
    * @return void
    */
        public function start() {
         self::$_transaction = Yii::app()->db->beginTransaction();
         return true;
        }

        /**
    * Откат транзакции
    *
    * @return bool true
    */
        public function rollBack() {
         self::$_transaction->rollBack();
         return true;
        }

        /**
    * Коммит транзакции
    *
    * @return bool true
    */
        public function commit() {
         self::$_transaction->commit();
         return true;
        }

        /**
    * Создает урл из названия
    *
    * @param string $title
    * @return string
    */
        public function createUrlName($title) {
            static $cyr = array(
                "Щ", "Ш", "Ч", "Ц","Ю", "Я", "Ж", "А","Б","В","Г","Д","Е","Ё","З","И","Й","К","Л","М","Н","О","П","Р","С","Т","У","Ф","Х", "Ь" ,"Ы","Ъ","Э","Є","Ї",
                "щ", "ш", "ч", "ц","ю", "я", "ж", "а","б","в","г","д","е","ё","з","и","й","к","л","м","н","о","п","р","с","т","у","ф","х", "ь","ы","ъ","э","є","ї"," ", "_"
            );
            static $lat = array(
                "Shh","Sh","Ch","C","Ju","Ja","Zh","A","B","V","G","D","Je","Jo","Z","I","J","K","L","M","N","O","P","R","S","T","U","F","Kh","","Y","","E","Je","Ji",
                "shh","sh","ch","c","ju","ja","zh","a","b","v","g","d","e","jo","z","i","j","k","l","m","n","o","p","r","s","t","u","f","kh","","y","","e","e","ji", "-", "-"
            );

            return strtolower(str_replace($cyr, $lat, trim($title)));
        }

        public function safePermalink(){
            $item = Item::model()->findByAttributes(array('permalink'=>$this->permalink));
            if(count($item)>0){
                $this->editPermalink();
                $this->safePermalink();
            }else{
                return true;
            }
        }

        public function editPermalink(){
            $this->permalink = $this->permalink.'2';
        }
    }